package com.it.xuehang.exception;


import com.it.xuehang.util.ResponseResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author:xue
 * @Date:
 * @Description: 全局异常处理器
 * @Version: 1.0
 */
@ControllerAdvice //@Controller+@Advice
public class GlobalExceptionHandler {


	//自定义失败异常
	@ExceptionHandler(FailedException.class)//ArithmeticException 1/0
	@ResponseBody
	public ResponseResult<Void> handleFailedException(Exception e){
		//控制台输出信息
		e.printStackTrace();
		ResponseResult<Void> result=new ResponseResult<>(255,e.getMessage());
		return result;
	}

	@ExceptionHandler(ValidationFailedException.class)//自定义验证异常.服务端异常
	@ResponseBody
	public ResponseResult<Map<String,String>> handleIOException(ValidationFailedException result){
		//响应给浏览器
		List<FieldError> errors = result.getResult().getFieldErrors();
		Map<String,String> errorInfos = new HashMap<>();
		for(FieldError e:errors){
			String attrName = e.getField();//验证失败的字段名称
			String message = e.getDefaultMessage();//验证失败提示信息
			System.out.println(attrName+"失败原因"+ message);
			if(errorInfos.containsKey(attrName)){
//				String temp = message;
//				message+=";"+temp;
				continue;
			}
			errorInfos.put(attrName,message);
		}
		return new ResponseResult<>(501,"提交数据有误,请重新修改并提交",errorInfos);
	}

}
